package com.sm.utils;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    private String role_admin = "ROLE_ADMIN";
    private String role_manager = "ROLE_MANAGER";


    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

//        使用迭代器读取数组
        Iterator it = authorities.iterator();
        SimpleGrantedAuthority role=null;
        while(it.hasNext()){
            role = (SimpleGrantedAuthority)it.next();
            if(role.getAuthority().equals(role_admin)||role.getAuthority().equals(role_manager)){
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/admin/main");
                return;
            }
        }
        httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/bss/home");

//        System.out.println(authorities.toString());//[ROLE_ADMIN]
    }
}

//        被强制类型转换的实例需要是强制类型转换类型的类或者其子类
//        Object[] 无法转成其他类
//        SimpleGrantedAuthority[] objects = (SimpleGrantedAuthority[]) authorities.toArray();
//        for (SimpleGrantedAuthority simpleGrantedAuthority :objects) {
//            if (simpleGrantedAuthority.getAuthority().equals(role_admin)) {
//                httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/admin/main");
//                return;
//            }
//        }

//        使用toArray（T[] a）的方法获取数组
//        SimpleGrantedAuthority[] objects = new SimpleGrantedAuthority[10];
//        objects = authorities.toArray( objects);
//        for (SimpleGrantedAuthority simpleGrantedAuthority :objects){
//            if(simpleGrantedAuthority.getAuthority().equals(role_admin)){
//                httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/admin/main");
//                return;
//            }
//        }
//        httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/bss/home");
